#!/bin/bash

export PATH=$JAVA_HOME/bin:$PATH
ROOT_PATH=$(cd "$(dirname $0)"; pwd)
JAR_FULL_PATH=$(find $ROOT_PATH -maxdepth 1 -name "*.jar")
JAR_NAME=${JAR_FULL_PATH##*/}

JAVA_OPTS="-server -Xms1024m -Xmx2048m -Xmn256m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m -Djava.awt.headless=true"

function killProsess() {
        NAME=$1
        echo $NAME

        PID=$(ps -ef|grep $NAME |grep -v 'grep'|awk '{print $2}')

        echo "PID: $PID"

        if [[ ! $PID ]]; then
                echo no pid , already stop!!!
        else
                kill -15 $PID
                echo done, stop complete!!!
        fi
}

function start() {
        echo "start by " $(whoami)
        echo "----------------"
        JAR_BIN="cd ${ROOT_PATH}" && nohup java ${JAVA_OPTS} -classpath lib\*.jar -jar ${JAR_NAME} --spring.profiles.active=prod > /dev/null 2>&1 &
        if [ $(whoami) = "root" ]; then
                su - lsms -c "${JAR_BIN}"
                echo done!!! execute command : su - lsms -c "${JAR_BIN}" 
        else
                $JAR_BIN
                echo done!!! execute command : "${JAR_BIN}"
        fi
}

function stop() {
        echo "stop"
        echo "----------------"
        killProsess ${JAR_NAME}
}

function restart() {
        echo "restart"
        echo "----------------"
        stop
        start
}

case "$1" in
        start )
                echo "****************"
                start
                echo "****************"
                ;;
        stop )
                echo "****************"
                stop
                echo "****************"
                ;;
        restart )
                echo "****************"
                restart
                echo "****************"
                ;;
        * )
                echo "****************"
                echo "no command"
                echo "****************"
                ;;
esac